package com.example.auth.filter;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.example.utils.AuthCode;
import org.example.utils.JWTUtil;
import org.example.utils.ResultTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
@WebFilter(urlPatterns = "/*", filterName = "jwtFilter")  //这里的“/*” 表示的是需要拦截的请求路径
public class JWTFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        String servletPath = httpServletRequest.getServletPath();  //获取客户端所请求的脚本文件的文件路径
        //不过滤处理无需权限控制的页面、JS和CSS文件
            if (!servletPath.contains("/itripUser/") && !servletPath.endsWith(".js") && !servletPath.endsWith(".css"))
            {
                if (JWTUtil.verify(httpServletRequest.getHeader("token"))) {
                    filterChain.doFilter(servletRequest,servletResponse);
                }else {
                    httpServletResponse.setHeader("Content-type", "text/html;charset=UTF-8");//告知浏览器编码方式;
                    servletResponse.setCharacterEncoding("UTF-8");
                    PrintWriter writer = httpServletResponse.getWriter();
                    writer.println(JSONObject.toJSONString(new ResultTemplate<>(AuthCode.AUTH_TOKEN_ERROR)));
                    writer.flush();writer.close();
                }
            }else{
                filterChain.doFilter(servletRequest,servletResponse);
            }
    }

    @Override
    public void destroy() {

    }
}
